package pers.ree.demo.datastructure;

import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapDemo {

    /**
     * 为什么用迭代器remove不会抛ConcurrentModificationException异常，
     * 因为相比直接用map的remove，迭代器的remove底层有expectedModCount = modCount的逻辑
     */
    @Test
    public void removeSuccess() {
        HashMap<String, String> map = new HashMap<>();

        map.put("a", null);
        map.put("b", null);
        map.put("c", null);

        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            iterator.next();
            iterator.remove();
        }

        System.out.println(map);
    }

    /**
     * remove时为什么会抛ConcurrentModificationException异常：
     * remove时modCount++了，导致expectedModCount!=modCount
     */
    @Test
    public void removeException() {
        HashMap<String, String> map = new HashMap<>();

        map.put("a", null);
        map.put("b", null);
        map.put("c", null);

        for (String key: map.keySet()) {
            // ConcurrentModificationException
            map.remove(key);
        }

        System.out.println(map);
    }
}
